package comp6231.project.common;

import java.io.*;

public class Utils {

	// http://cboard.cprogramming.com/windows-programming/113352-udp-max-datagram-size.html
	public static final int UDP_DATAGRAM_MAX_SIZE = 508;
	
	/**
	 * Serialize object into byte buffer
	 * @param obj Object to be serialized
	 * @return Byte buffer contains the object if successful, null otherwise
	 */
	public static byte[] toBytes(Serializable obj) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = null;
		try {
		  out = new ObjectOutputStream(bos);   
		  out.writeObject(obj);
		  byte[] buf = bos.toByteArray();
		  return buf;
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				out.close();
				bos.close();
			} catch (IOException ex) {				
			}
		}
		return null;
	}
	
	/**
	 * Deserialize object from byte buffer
	 * @param buf Byte buffer contains the object
	 * @return Object being deserialized if successful, null otherwise
	 */
	public static Object fromBytes(byte[] buf) {
		ByteArrayInputStream bis = new ByteArrayInputStream(buf);
		ObjectInput in = null;
		try {
		  in = new ObjectInputStream(bis);
		  Object obj = in.readObject(); 
		  return obj;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				bis.close();
				in.close();
			} catch (IOException ex) {				
			}
		}
		return null;
	}	
}
